package cn.tedu.csmall.passport.controller;

import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginInfoDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminUpdateInfoDTO;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.security.LoginPrincipal;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.passport.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admins")
@Api(tags = "01. 管理员管理模块")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    public AdminController() {
        log.info("创建控制器：AdminController");
    }

    // http://localhost:9081/admins/login
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 88)
    @PostMapping("/login")
    public JsonResult<String> login(AdminLoginInfoDTO adminLoginInfoDTO) {
        log.debug("开始处理【登录认证】的请求，参数：{}", adminLoginInfoDTO);
        String jwt = adminService.login(adminLoginInfoDTO);
        log.debug("即将向客户端响应JWT数据：{}", jwt);
        return JsonResult.ok(jwt);
    }

    // http://localhost:9081/admins/add-new
    @ApiOperation(value = "添加管理员", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/add-new")
    public JsonResult<Void> addNew(AdminAddNewDTO adminAddNewDTO) {
        log.debug("开始处理【添加管理员】的请求，参数：{}", adminAddNewDTO);
        adminService.addNew(adminAddNewDTO);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/5/delete
    @ApiOperation(value = "根据id删除管理员", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "long")
    @PreAuthorize("hasAuthority('/ams/admin/delete')")
    @PostMapping("/{id:[0-9]+}/delete")
    public JsonResult<Void> deleteById(@PathVariable Long id) {
        log.debug("开始处理【根据id删除管理员】的请求：id={}", id);
        adminService.deleteById(id);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/5/password/change
    @ApiOperation(value = "修改管理员密码", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "long"),
            @ApiImplicitParam(name = "password", value = "新密码", required = true, dataType = "string"),
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/{id:[0-9]+}/password/change")
    public JsonResult<Void> updatePasswordById(@PathVariable Long id, String password) {
        log.debug("开始处理【修改管理员密码】的请求，id={}，password={}", id, password);
        adminService.updatePasswordById(id, password);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/5/info/update
    @ApiOperation(value = "修改管理员基本资料", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 301)
    @ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "long")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/{id:[0-9]+}/info/update")
    public JsonResult<Void> updateInfoById(@PathVariable Long id, AdminUpdateInfoDTO adminUpdateInfoDTO) {
        log.debug("开始处理【修改管理员基本资料】的请求，id={}，新基本资料={}", adminUpdateInfoDTO);
        adminService.updateInfoById(id, adminUpdateInfoDTO);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/5/enable
    @ApiOperation(value = "启用管理员账号", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "long")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/{id:[0-9]+}/enable")
    public JsonResult<Void> setEnable(@PathVariable Long id) {
        log.debug("开始处理【启用管理员账号】的请求：id={}", id);
        adminService.setEnable(id);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/5/disable
    @ApiOperation(value = "禁用管理员账号", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 311)
    @ApiImplicitParam(name = "id", value = "管理员id", required = true, dataType = "long")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/{id:[0-9]+}/disable")
    public JsonResult<Void> setDisable(@PathVariable Long id) {
        log.debug("开始处理【禁用管理员账号】的请求：id={}", id);
        adminService.setDisable(id);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins
    @ApiOperation(value = "查询管理员列表", notes = "请求头中必须携带名为Authorization的JWT，且对应的用户必须具有相关权限")
    @ApiOperationSupport(order = 400)
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @GetMapping("")
    public JsonResult<List<AdminListItemVO>> list(
            @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【查询管理员列表】的请求……");
        log.debug("从SecurityContext中获取到的当事人（当前JWT表示的用户）的id：{}", loginPrincipal.getId());
        log.debug("从SecurityContext中获取到的当事人（当前JWT表示的用户）的用户名：{}", loginPrincipal.getUsername());
        List<AdminListItemVO> list = adminService.list();
        return JsonResult.ok(list);
    }

}
